# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(plyr)
library(dplyr)
library(tidyr)
library(tibble)
library(gridExtra)
library(purrr)
library(scales)
library(egg)
library(VennDiagram)
library(optparse)
library(magrittr)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
  set_colnames(c("arg", "value")) %>%
  column_to_rownames("arg")

configData

pValue <- configData["diffMethod.kwP", "value"] %>%
  as.numeric()
fdr <- configData["diffMethod.kwFdr", "value"] %>%
  as.numeric()

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))

sampleIds <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote")) %>%
  .$SampleID

inputData <- read.csv(opt$i, header = T, stringsAsFactors = F) %>%
  select(c("Class", "HMDB", "KEGG", "Metabolite", sampleIds))

data <- inputData %>%
  select(-c("HMDB", "KEGG", "Class"))

head(data)

classData <- inputData %>%
  select(c("Class", "HMDB", "KEGG", "Metabolite"))

head(classData)

parent <- "./"
createWhenNoExist(parent)
uniFileName <- paste0("../uni/", parent, "/AllMet_Test.csv")
uniData <- read.csv(uniFileName, header = T, stringsAsFactors = F, comment.char = "") %>%
  rowwise() %>%
  do({
       result <- as.data.frame(.)
       p <- result[1, "P"]
       q <- result[1, "FDR"]
       print(p)
       value <- if (p < pValue) {
         1
       }else 0
       result$IS_Uni_P_Sig <- value
       result$IS_Uni_FDR_Sig <- ifelse(q <= fdr, 1, 0)
       result$IS_Sig <- as.numeric(result$IS_Uni_FDR_Sig &
                                     result$IS_Uni_P_Sig)
       result
     }) %>%
  mutate(Uni_P = P, Uni_FDR = FDR) %>%
  select(c("Metabolite", "Uni_P", "IS_Uni_P_Sig", "Uni_FDR", "IS_Uni_FDR_Sig", "IS_Sig"))
print(head(uniData))

finalDf <- classData %>%
  left_join(uniData, by = c("Metabolite")) %>%
  left_join(data, by = c("Metabolite"))

head(finalDf)


outFileName <- paste0(parent, "/AllMet_Test.csv")
write.csv(finalDf, outFileName, row.names = F)





